package com.putao.album.main.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.putao.album.R;
import com.putao.album.child.bean.FamilyItem;
import com.putao.album.child.bean.RelationItem;
import com.putao.album.util.BitmapHelper;
import com.putao.album.widget.rounder.RoundImageView;

import java.util.ArrayList;

/**
 * Created by jidongdong on 15/6/13.
 */
public class HomeFamilyLinearLayout extends ViewGroup {
    private ArrayList<FamilyItem> familyItems;
    private int mImageViewWidth;
    private int mImageViewHeight;
    private Drawable mDefaultDrawable;

    private OnAvatarOnClickListener mOnAvatarOnClickListener;

    public HomeFamilyLinearLayout(Context context) {
        super(context);
        init();
    }

    public HomeFamilyLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public HomeFamilyLinearLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }


    public void setOnAvatarOnClickListener(OnAvatarOnClickListener listener) {
        mOnAvatarOnClickListener = listener;
    }

    void init() {
        mDefaultDrawable = getResources().getDrawable(R.drawable.head_more);
        mImageViewWidth = mDefaultDrawable.getIntrinsicWidth() + 10;
        mImageViewHeight = mDefaultDrawable.getIntrinsicHeight();
    }

    public ArrayList<FamilyItem> getFamilyItems() {
        return familyItems;
    }

    public void setFamilyItems(ArrayList<FamilyItem> familyItems) {
        this.familyItems = familyItems;
        loadAvatars(familyItems);
    }

    /**
     * 加载头像
     *
     * @param familyItems
     */
    private void loadAvatars(ArrayList<FamilyItem> familyItems) {
        if (familyItems == null) {
            return;
        }
        addAvatars(familyItems, familyItems.size());
    }

    /**
     * 从所有头像中加载部分头像
     *
     * @param familyItems
     * @param count
     */
    private void addAvatars(ArrayList<FamilyItem> familyItems, int count) {
        for (int i = 0; i < count; i++) {
            addImageView(familyItems.get(i));
        }
    }

    /**
     * 添加ImageView
     *
     * @param item
     */
    private void addImageView(FamilyItem item) {
        ImageView imageView = new RoundImageView(getContext());
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(mImageViewWidth, mImageViewHeight);
        imageView.setLayoutParams(lp);
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(RelationItem.Tag.getResIdByTag(item.getTag()))
                .showImageOnLoading(BitmapHelper.getLoadingDrawable()).showImageOnFail(BitmapHelper.getLoadingDrawable())
                .cacheOnDisk(true).cacheInMemory(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .considerExifParams(true)
                .build();
        ImageLoader.getInstance().displayImage(item.getAvatar(), imageView, options);
        imageView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnAvatarOnClickListener != null) {
                    mOnAvatarOnClickListener.onClick();
                }
            }
        });
        addView(imageView);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // 创建测量参数
        int cellWidthSpec = MeasureSpec.makeMeasureSpec(mImageViewWidth, MeasureSpec.AT_MOST);
        int cellHeightSpec = MeasureSpec.makeMeasureSpec(mImageViewHeight, MeasureSpec.AT_MOST);
        // 记录ViewGroup中Child的总个数
        int count = getChildCount();
        // 设置子空间Child的宽高
        for (int i = 0; i < count; i++) {
            View childView = getChildAt(i);
            childView.measure(cellWidthSpec, cellHeightSpec);
        }
        // 设置容器控件所占区域大小
        // 注意setMeasuredDimension和resolveSize的用法
        setMeasuredDimension(resolveSize(mImageViewWidth * count, widthMeasureSpec),
                resolveSize(mImageViewHeight, heightMeasureSpec));
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int cellWidth = mImageViewWidth;
        int cellHeight = mImageViewHeight;
        int columns = (r - l) / cellWidth;
        if (columns < 0) {
            columns = 1;
        }
        int x = 0;
        int y = 0;
        int count = getChildCount();
        int size = count <= columns ? count : columns;
        for (int j = 0; j < size; j++) {
            final View childView = getChildAt(j);
            if (j == size - 1 && count > columns) {
                ImageView imageView = (ImageView) childView;
                imageView.setImageDrawable(mDefaultDrawable);
            }
            // 获取子控件Child的宽高
            int w = childView.getMeasuredWidth();
            int h = childView.getMeasuredHeight();
            // 计算子控件的顶点坐标
            int left = x + ((cellWidth - w) / 2);
            int top = y + ((cellHeight - h) / 2);
            // 布局子控件
            childView.layout(left, top, left + w + 10, top + h);
            x += cellWidth;
        }
    }

    public interface OnAvatarOnClickListener {
        void onClick();
    }
}
